#pragma once
#include <iostream>
#include <string>

#include "Log.hpp"
#include "init.hpp"

extern Log lg;
Init init;


class Task
{
public:
    Task(int sockfd, const std::string &clientip, const uint16_t &clientport)
        : _sockfd(sockfd), _clientip(clientip), _clientport(clientport)
    {
    }
    Task()
    {
    }
    void run()
    {
        char buffer[4096];
        ssize_t n = read(_sockfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client key: " << buffer << std::endl;
            std::string echo_string = init.translate(buffer);
            //write(_sockfd, echo_string.c_str(), echo_string.size());

            //sleep(5);
            //lg(Warning, "close sockfd done  %d", _sockfd);
            //sleep(2);
            int m = write(_sockfd, echo_string.c_str(), echo_string.size());
            if(m < 0)
            {
                lg(Warning, "write erroe, errno: %d, errstring: %s", errno,strerror(errno));
            }
        }
        else if (n == 0)
        {
            lg(Info, "%s:%d quit, server close sockfd:%d", _clientip.c_str(), _clientport, _sockfd);
        }
        else
        {
            lg(Warning, "%s:%d read error, close sockfd:%d", _clientip.c_str(), _clientport, _sockfd);
        }
        close(_sockfd);
    }
    void operator()()
    {
        run();
    }

    ~Task()
    {
    }

private:
    int _sockfd;
    std::string _clientip;
    uint16_t _clientport;
};